package net.sahv.bdyz.controller.web;

import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;

import net.sahv.bdyz.model.Fabric;
import net.sahv.bdyz.model.Member;
import net.sahv.bdyz.model.MemberAttention;
import net.sahv.bdyz.model.Pattern;
import net.sahv.bdyz.model.PatternFilter;
import net.sahv.bdyz.service.FabricService;
import net.sahv.bdyz.service.MemberAttentionService;
import net.sahv.bdyz.service.MemberService;
import net.sahv.bdyz.service.PatternFilterService;
import net.sahv.bdyz.service.PatternService;
import net.sahv.bdyz.util.Base64;
import net.sahv.bdyz.util.ImagePHash;
import net.sahv.bdyz.util.LoadCfgUtil;
import net.sahv.bdyz.util.PageInfo;

@Controller
@RequestMapping("web/patternfilter/")
public class PatternFilterController {
	@Autowired
	private MemberService memberService;
	@Autowired
	private PatternFilterService patternFilterService;
	@Autowired
	private PatternService patternService;
	@Autowired
	private FabricService fabricService;
	@Autowired
	private MemberAttentionService memberattentionService;
	@Autowired 
	CookieLocaleResolver resolver;
	@RequestMapping(value = "{canshu}/flowertypecatalog{page}", method = RequestMethod.GET)
	public String doposition(HttpServletRequest request,HttpServletResponse response,Model model, @PathVariable(value = "canshu") String canshu, @PathVariable(value = "page") String page) throws FileNotFoundException, IOException {
		Object languageObj=request.getSession().getAttribute("language");
		
		Map<String, String> mapUrls = LoadCfgUtil.loadCfg();
		
		model.addAttribute("imgpath",mapUrls.get("targetUrl.img"));
		
		
		 String yuyan="";
		if(languageObj!=null){
			String language=String.valueOf(languageObj);
			if(language!=null&&!language.equals("")){
				language=language.toLowerCase();
				if(language.equals("zh_cn")){
					yuyan="ch";
					resolver.setLocale(request, response, Locale.CHINA );
				}else if(language.equals("en")){
					yuyan="en";
					resolver.setLocale(request, response, Locale.ENGLISH );
				}else{
					yuyan="ch";
					resolver.setLocale(request, response, Locale.CHINA );
				}
			}
		}else{
			yuyan="ch";
		}
		model.addAttribute("yuyan", yuyan);
		Member member = memberService.getCurrent();//获取当前登录人信息
		if(canshu.indexOf("02")>=0){
		if(member==null){
			return "redirect:/web/patternfilter/all/flowertypecatalog1";
		}else{
			if(member.getmVip()==0){//不是vip
				return "redirect:/web/patternfilter/all/flowertypecatalog1";				
			}
		}
		}
		List<Map<String, Object>> zong = new ArrayList<>();
		List<PatternFilter> list = patternFilterService.selectAllBypid(0,yuyan);
		for (PatternFilter item : list) {
			Map<String, Object> map = new HashMap<String, Object>();
			List<PatternFilter> zilist = patternFilterService.selectAllBypid(item.getPtId(),yuyan);
			map.put("fuji", item);
			map.put("zi", zilist);
			zong.add(map);
		}
		model.addAttribute("shuju", zong);
		model.addAttribute("canshu", canshu);

		// 查询
		PageInfo pageInfo = new PageInfo();
		if(page.equals("")){
			page="1";
		}
		pageInfo.setPage(Integer.valueOf(page));
		pageInfo.setPageSize(20);
		
		List<Map<String, Object>> pattern = patternService.findAll(pageInfo, canshu, " ORDER BY ",member);
		model.addAttribute("pattern", pattern);
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("member", member);
		return "web/patternfilter/flowertypecatalog";
	}
	
	/**
	 * 以图搜图  王聪朝  2016年8月15日16:58:52
	 * @param request
	 * @param response
	 * @param model
	 * @param canshu
	 * @param page
	 * @return
	 * @throws Exception 
	 */
	
	@RequestMapping(value = "flowertypecatalog{page}")
	public String dopositionByImg(HttpServletRequest request,HttpServletResponse response,Model model,String fileImg,String page,String key) throws Exception {
		// key = new String(key.getBytes("ISO-8859-1"), "utf-8");
		Object languageObj=request.getSession().getAttribute("language");
		String yuyan = "";
		if(languageObj!=null){
			String language=String.valueOf(languageObj);
			if(language!=null&&!language.equals("")){
				language=language.toLowerCase();
				if(language.equals("zh_cn")){
					yuyan="ch";
					resolver.setLocale(request, response, Locale.CHINA);
				}else if(language.equals("en")){
					yuyan="en";
					resolver.setLocale(request, response, Locale.ENGLISH);
				}else{
					yuyan="ch";
					resolver.setLocale(request, response, Locale.CHINA);
				}
			}
		}else{
			yuyan="ch";
		}
		model.addAttribute("yuyan", yuyan);
		Member member = memberService.getCurrent();//获取当前登录人信息
		List<Map<String, Object>> zong = new ArrayList<>();
		List<PatternFilter> list = patternFilterService.selectAllBypid(0,yuyan);
		for (PatternFilter item : list) {
			Map<String, Object> map = new HashMap<String, Object>();
			List<PatternFilter> zilist = patternFilterService.selectAllBypid(item.getPtId(),yuyan);
			map.put("fuji", item);
			map.put("zi", zilist);
			zong.add(map);
		}
		model.addAttribute("shuju", zong);
		model.addAttribute("canshu", "all");
		// 查询
		PageInfo pageInfo = new PageInfo();
		if(page==null||page.equals("")){
			page="1";
		}
		pageInfo.setPage(Integer.valueOf(page));
		pageInfo.setPageSize(20);
		ImagePHash push = new ImagePHash();
     	Base64 bb=new Base64();
     	String where="1=1";
		if(fileImg!=null&&!fileImg.equals(""))
     	{
     		fileImg = fileImg.substring(fileImg.indexOf(",")+1, fileImg.length());
     	    byte[] bytes=bb.decode(fileImg);
     	    String imgSerial=push.getHash(byteTOInputStream(bytes));	     		
 	     	//添加搜索图片条件
	        where+=" AND P_BUYOUT_STATE=0 and P_VIP!='4' and getCounter(P_MESSAGE1,'"+imgSerial+"')<20 and P_MESSAGE1!='' AND !isnull(P_MESSAGE1)";
     	}
		else
     	{
     		if (key != null && !key.equals("")) {	    		
    			if (key.contains("'")) {
    				key = key.replaceAll("'", "''");
				}
				// 根据key查询所有相关标签
				/*
				 * List<PatternFilter> pfList = patternFilterService
				 * .selectByName(" (PT_NAME like '%" + key +
				 * "%' or PT_NAME_EN like '%" + key + "%')"); String pfIds = "";
				 * if (pfList != null && pfList.size() > 0) { for (PatternFilter
				 * pf : pfList) { pfIds += " find_in_set('" + pf.getPtId() +
				 * "', TIAOJIAN) or"; } } if (pfIds != "") { pfIds =
				 * pfIds.substring(0, pfIds.length() - 2); where += " and (" +
				 * pfIds + ")"; }
				 */
				where += " AND P_BUYOUT_STATE=0 and P_VIP!='4' and  (P_NO  like '" + "%" + key
						+ "%' or P_MESSAGE2 like '%" + key + "%') ";
    		} 	     		
     	}
		List<Map<String, Object>> pattern = patternService.findAllByImg(pageInfo, "all", " ORDER BY P_ID DESC ",member,where);
		
		Map<String, String> mapUrls = LoadCfgUtil.loadCfg();
		model.addAttribute("imgpath",mapUrls.get("targetUrl.img"));
		model.addAttribute("pattern", pattern);
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("member", member);
		model.addAttribute("fileImg", fileImg);
		return "web/patternfilter/flowertypecatalog";
	}
	
	 /**
     * 将byte数组转换成InputStream
     * @param in
     * @return 王聪朝2016年8月16日10:23:20
     * @throws Exception
     */
    public static InputStream byteTOInputStream(byte[] in) throws Exception{         
        ByteArrayInputStream is = new ByteArrayInputStream(in);
        return is;
    }
	/**
	 * 判断是否是vip
	 * @author 薛国计
	 * @date 2016年8月5日
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "judge", method = RequestMethod.POST)
	public ApiResult judge(HttpServletRequest request) {
		ApiResult result = new ApiResult();
		Member member = memberService.getCurrent();//获取当前登录人信息
		if(member==null){
			result.msg.status=1;//未登录
			result.msg.desc="未登录";
		}else{
			Member member1 = memberService.selectByPrimaryKey(member.getmId());
			if(member1.getmVip()==0){//不是vip
				result.msg.status=2;//不是vip
				result.msg.desc="不是vip";
			}else{//更新session
				request.getSession().setAttribute("member", member1);
			}
		}
		return result;
	
	}
	/**
	 * 关注花型
	 * @author 薛国计
	 * @date 2016年8月8日
	 * @param request
	 * @param pId 花型id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "collect", method = RequestMethod.POST)
	public ApiResult collect(HttpServletRequest request,String pId) {
		Member member = memberService.getCurrent();//获取当前登录人信息
		MemberAttention memberattention = new MemberAttention();
		memberattention.setAtttype(2);
		memberattention.setAttid(Integer.valueOf(pId));
		memberattention.setCreatetime(new Date());
		memberattention.setIsdelete(0);
		memberattention.setMid(member.getmId());
		ApiResult result = new ApiResult();
		int i = patternService.guanzhu(Integer.valueOf(pId));
		int y = memberattentionService.insert(memberattention);
		if(i>0&&y>0){
			result.msg.status=0;
			result.msg.desc="操作成功！";
			return result;
		}
		result.msg.status=1;
		result.msg.desc="操作失败！";
		return result;
	}
	/**
	 * 取消关注
	 * @author 薛国计
	 * @date 2016年8月12日
	 * @param request
	 * @param pId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "delcollect", method = RequestMethod.POST)
	public ApiResult delcollect(HttpServletRequest request,String pId) {
		Member member = memberService.getCurrent();//获取当前登录人信息		
		MemberAttention memberattention = memberattentionService.findBycollect(Integer.valueOf(pId),member.getmId());
		
		ApiResult result = new ApiResult();
		int i = patternService.quxiaoguanzhu(Integer.valueOf(pId));
		int y = memberattentionService.delete(memberattention.getId());
		if(i>0&&y>0){
			return result;
		}
		result.msg.status=1;
		result.msg.desc="操作失败";
		return result;
	}
	
	@RequestMapping(value = "viewpattern", method = RequestMethod.GET)
	public String viewpattern(HttpServletRequest request,String pNo) {
		Pattern pattern =patternService.selectByNo(pNo);
		return "redirect:/web/pattern/flowerCatalog?id="+pattern.getpId();
	}
	
	@RequestMapping(value = "viewf", method = RequestMethod.GET)
	public String viewf(HttpServletRequest request,String fNo) {
		Fabric fabric =fabricService.selectByNo(fNo);
		return "redirect:/web/fabric/detail?fId="+fabric.getfId();
	}
	
	
	
	
}
